<?php

/**
 * 搜索与查询
 */

namespace Logic;

class Search {

    private $q = ''; // 查询内容
    private $keyword = ''; // 查询关键词
    private $product_id = 0; // 产品id
    private $pageSize = 20;
    private $taocode = '';
    private $has_quan = false;
    private $link = '';
    private $return = [
        'totalCount' => 0,
        'totalPage' => 0,
        'dataList' => [],
        'nowPage' => 1,
        'title' => '',
    ];

    /**
     * 构造函数
     * @param string $q 查询的内容
     * @param integer $page 查询分页
     */
    public function __construct($q = '', $page = 1, $has_quan = false) {
        $this->q = $q;
        $this->keyword = $q;
        $this->return['nowPage'] = $page > 100 ? 100 : $page;
        $this->return['title'] = $q;
        $this->has_quan = $has_quan;
    }

    /**
     * 开始查询
     */
    public function query() {
        // 判断查询类型
        $type = $this->getQueryType();
        switch ($type) {
            case 'taocode':
                $this->queryFromTaocode();
                break;
            case 'link':
                $this->queryFromLink();
                break;
        }

        // 正式查询
        $result = 0;
        if ($this->product_id) {
            $this->queryFromProductId();
            $result = $this->queryProduct();
        }

        if (!$result) {
            $this->queryFromKeyword();
        }

        return $this->return;
    }

    /**
     * 获取查询内容
     */
    public function getQueryData() {
        $type = $this->getQueryType();
        switch ($type) {
            case 'productid':
                return $this->product_id;
                break;
            case 'taocode':
                return $this->taocode;
                break;
            case 'link':
                return $this->link;
                break;
            default:
                return $this->q;
        }
    }

    /**
     * 查询类型
     */
    private function getQueryType() {

        if (is_numeric($this->q) && ctype_digit($this->q)) {
            $this->product_id = $this->q;
            $this->return['title'] = $this->q;
            $this->pageSize = 200;
            return 'productid'; // 商品id
        }

        if (strpos($this->q, 'https') !== false && strpos($this->q, 'item.htm?id=') && (strpos($this->q, 'taobao') || strpos($this->q, 'tmall'))) {
            $this->link = $this->return['title'] = $this->q;
            return 'link'; // 商品页链接
        }

        // 淘口令
        if (substr_count($this->q, '￥') == 2 || substr_count($this->q, '€') == 2 || substr_count($this->q, '$') == 2) {
            $taocode = $this->getTaocode($this->q);
            $this->taocode = $this->return['title'] = $taocode;
            return 'taocode'; // 淘口令
        }
    }

    /**
     * 淘口令查询
     */
    private function queryFromTaocode() {
        $result = \Logic\TaoApi::parseTaocode($this->q);
        if (!isset($result->content) || !isset($result->url)) {
            return ''; // 没有找到解析的内容
        }

        // 解析商品id
        $this->keyword = $result->content;
        $this->product_id = $this->getProductIdFromUrl($result->url);

        $this->pageSize = 100;
    }

    /**
     * 链接查询
     */
    private function queryFromLink() {
        $t = parse_url($this->q);
        if (!isset($t['query']) || !$t['query'] || strpos($t['query'], 'id=') === false) {
            return '';
        }

        $product_id = explode('=', $t['query'])[1];
        if ($product_id) {
            $this->product_id = $product_id;
        }
    }

    /**
     * 通过商品id查询
     */
    private function queryFromProductId() {
        // 查询接口
        $result = \Logic\TaoApi::getDetails([$this->product_id]);
        if (isset($result[$this->product_id])) {
            $this->return['title'] = mb_substr($result[$this->product_id]['title'], 0, 12, 'utf-8');
            $this->keyword = $result[$this->product_id]['title'];
        }
    }

    /**
     * 通过关键词查询
     */
    private function queryFromKeyword() {
        $result = \Logic\TaoApi::getProducts(0, $this->keyword, "100", $this->has_quan, $this->return['nowPage'], $this->pageSize);
        $this->return['totalCount'] = isset($result->total_results) ? $result->total_results : 0;
        $this->return['totalPage'] = isset($result->total_results) && ($result->total_results) ? ceil($result->total_results / $this->pageSize) : 0;
        $dataList = [];

        if (isset($result->result_list) && $result->result_list->map_data) {
            foreach ($result->result_list->map_data as $r) {
                $amount = 0;
                $coupon_share_url = '';
                if ($r->coupon_id) {
                    $time = time();

                    $coupon_remain_count = $r->coupon_remain_count;
                    $coupon_start_time = strtotime($r->coupon_start_time . ' 00:00:00');
                    $coupon_end_time = strtotime($r->coupon_end_time . ' 23:59:59');

                    if ($coupon_remain_count > 0 && $coupon_start_time < $time && $coupon_end_time > $time) {
                        $amount = \Logic\Coupon::getAmount($r->coupon_info);
                        $coupon_share_url = \Logic\Coupon::cleanCouponUrl($r->coupon_share_url);
                    }
                }
                $more = \Logic\Product::getMore($r->zk_final_price, $r->commission_rate, $amount);
                $click_url = \Logic\Product::cleanClickUrl($r->url);

                $tmp = [
                    $more['amount'],
                    $coupon_share_url ? $coupon_share_url : $click_url,
                    $more['red_packet'],
                ];

                if ($this->product_id && $r->num_iid == $this->product_id) {
                    $dataList = [];
                }

                $dataList[] = [
                    'product_id' => $r->num_iid,
                    'item_url' => $r->item_url,
                    'pict_url' => $r->pict_url,
                    'title' => $r->title,
                    'zk_final_price' => $r->zk_final_price,
                    'volume' => isset($r->volume) ? $r->volume : 0,
                    'commission_rate' => $r->commission_rate,
                    'red_packet' => sprintf("%01.2f", $more['red_packet']),
                    'amount' => $more['amount'],
                    'final_price' => sprintf("%01.2f", $more['final_price']),
                    'coupon_share_url' => $coupon_share_url,
                    'ext' => \Common::deflate_data(implode('-', $tmp)),
                    'item_description' => '',
                ];

                if ($this->product_id && $r->num_iid == $this->product_id) {
                    break;
                }
            }
        }

        $this->return['dataList'] = $dataList;
    }

    /**
     * 查询单个商品信息
     */
    private function queryProduct($page = 1) {
        $result = \Logic\TaoApi::getProducts(0, $this->keyword, "100", $this->has_quan, $page, $this->pageSize);
        $this->return['totalCount'] = 0;
        $this->return['totalPage'] = 0;
        $this->return['dataList'] = $dataList = [];

        if (isset($result->result_list) && $result->result_list->map_data) {
            foreach ($result->result_list->map_data as $r) {
                // 循环查找商品
                if ($r->num_iid != $this->product_id) {
                    continue;
                }

                $amount = 0;
                $coupon_share_url = '';
                if ($r->coupon_id) {
                    $time = time();
                    $coupon_remain_count = $r->coupon_remain_count;
                    $coupon_start_time = strtotime($r->coupon_start_time . ' 00:00:00');
                    $coupon_end_time = strtotime($r->coupon_end_time . ' 23:59:59');

                    if ($coupon_remain_count > 0 && $coupon_start_time < $time && $coupon_end_time > $time) {
                        $amount = \Logic\Coupon::getAmount($r->coupon_info);
                        $coupon_share_url = \Logic\Coupon::cleanCouponUrl($r->coupon_share_url);
                    }
                }
                $more = \Logic\Product::getMore($r->zk_final_price, $r->commission_rate, $amount);
                $click_url = \Logic\Product::cleanClickUrl($r->url);

                $tmp = [
                    $more['amount'],
                    $coupon_share_url ? $coupon_share_url : $click_url,
                    $more['red_packet'],
                ];

                $dataList[] = [
                    'product_id' => $r->num_iid,
                    'item_url' => $r->item_url,
                    'pict_url' => $r->pict_url,
                    'title' => $r->title,
                    'zk_final_price' => $r->zk_final_price,
                    'volume' => isset($r->volume) ? $r->volume : 0,
                    'commission_rate' => $r->commission_rate,
                    'red_packet' => sprintf("%01.2f", $more['red_packet']),
                    'amount' => $more['amount'],
                    'final_price' => sprintf("%01.2f", $more['final_price']),
                    'coupon_share_url' => $coupon_share_url,
                    'ext' => \Common::deflate_data(implode('-', $tmp)),
                    'item_description' => '',
                ];

                break;
            }

            if ($dataList) {
                $this->return['dataList'] = $dataList;
                return 1;
            }

            if (!$dataList) {
                $page++;
                $this->queryProduct($page);
            }
        }

        return 0;
    }

    /**
     * 解析url获取产品id
     */
    private function getProductIdFromUrl($url = '') {
        $return = 0;
        if (strpos($url, '.htm?') && strpos($url, 'https://a.m.taobao.com') !== false) {
            $tmp = explode('.htm?', $url)[0];
            $return = str_replace('https://a.m.taobao.com/i', '', $tmp);
        }

        if (strpos($url, 'https://detail.m.tmall.com') !== false || strpos($url, 'https://item.taobao.com') !== false) {
            $query = parse_url($url)['query'];
            $tmp = explode('&', $query);
            foreach ($tmp as $t) {
                $t = trim($t);
                if ($t && strpos($t, 'id=') !== false) {
                    $return = str_replace('id=', '', $t);
                    break;
                }
            }
        }

        return $return;
    }

    /**
     * 从字符串里筛出淘口令
     */
    private function getTaocode($string = '') {
        $split = '￥';
        if (strpos($string, '€') !== false) {
            $split = '€';
        }

        if (strpos($string, '$') !== false) {
            $split = '$';
        }

        return $split . explode($split, $string)[1] . $split;
    }

}
